package com.hxm.appGenealogy.controller;

import com.alibaba.fastjson.JSON;
import com.hxm.appGenealogy.Function.FamilyFunction;
import com.hxm.appGenealogy.Function.PeopleFunction;
import com.hxm.appGenealogy.config.ParmIntended;
import com.hxm.appGenealogy.config.SignV3Utils;
import com.hxm.appGenealogy.config.client.SdkClient;
import com.hxm.appGenealogy.config.queryVo.QueryWrapperVO;
import com.hxm.appGenealogy.entity.Pay;
import com.hxm.appGenealogy.entity.People;
import com.hxm.appGenealogy.entity.ResponDataVo;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;

@RestController
@RequestMapping("app/pay")
public class PayController {

    @Autowired
    private FamilyFunction familyFunction;


    @Autowired
    private PeopleFunction peopleFunction;

    @Autowired
    private ExecutorService executorService;


    private final String appid = "wx35c01cabe7298eda";

    private final String mchid = "1624602016";

    private final String notify_url = "https://q3dsafiqrff3.ngrok.xiaomiqiu123.top/app/pay/appWxpayNotify";

    private final String url = "https://api.mch.weixin.qq.com/v3/pay/transactions/app";


    private final String apiV3 = "WRTGSR3t2t41t251344G252GSw4tw134";


    @PostMapping("appWxpay")
    public ResponDataVo appPay(@RequestBody Pay pay) {
        String parmAnalysis = ParmIntended.parmAnalysis(pay, "peopleId", "money");
        if (parmAnalysis != null) {
            return new ResponDataVo(parmAnalysis);
        }
        People people = peopleFunction.queryGetOneString(JSON.toJSONString(new QueryWrapperVO().eq("id", pay.getPeopleId())));
        if (people == null) {
            return new ResponDataVo("没有发现当前的人员的数据的信息;");
        }
        Map<String, Object> payParmMap = new LinkedHashMap<>();
        payParmMap.put("appid", appid);
        payParmMap.put("mchid", mchid);
        payParmMap.put("description", "家园app-svip");    //商品描述;
        String s = UUID.randomUUID().toString();
        payParmMap.put("out_trade_no", s.substring(s.length() - 18, s.length() - 1));    //商品订单号;
        payParmMap.put("notify_url", notify_url);    //商品订单号;
        payParmMap.put("attach", JSON.toJSONString(pay));    //商品订单号;
        Map<String, Object> amountMap = new LinkedHashMap<>();
        amountMap.put("total", Math.round(pay.getMoney() * 100));  //金额
        amountMap.put("currency", "CNY"); //货币类型;
        payParmMap.put("amount", amountMap);
        String resultPost = null;
        try {

            HashMap<String, String> headMap = SignV3Utils.getSignMap("POST", "https://api.mch.weixin.qq.com/v3/pay/transactions/app", JSON.toJSONString(payParmMap));
            resultPost = SdkClient.post(url, JSON.toJSONString(payParmMap), headMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> resultMap = (Map<String, Object>) JSON.parse(resultPost);
        String prepay_id = (String)resultMap.get("prepay_id");
        Map<String,Object> resultMapData = new HashMap<>();
        resultMapData.put("appid",appid);
        resultMapData.put("partnerid",mchid);
        resultMapData.put("prepayid",prepay_id);
        resultMapData.put("package","Sign=WXPay");
        resultMapData.put("noncestr",s);
        resultMapData.put("timestamp",System.currentTimeMillis());
        String buildMessage = buildMessage(appid, System.currentTimeMillis(), s, prepay_id);
        try {
            String sign = SignV3Utils.sign(buildMessage.getBytes(StandardCharsets.UTF_8));
            resultMapData.put("sign",sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponDataVo(true, "SUCCESS", resultMapData);
    }





    String buildMessage(String appid, long timestamp,String nonceStr,String prepay_id) {

        return appid + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + prepay_id + "\n";
    }


    @PostMapping("appWxpayNotify")
    public Map<String, Object> nutifyUrl(@RequestBody Map<String, Object> requestParmAsMap, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        String event_type = (String) requestParmAsMap.get("event_type");
        String resource_type = (String) requestParmAsMap.get("resource_type");
        if (!event_type.equals("TRANSACTION.SUCCESS") || !resource_type.equals("encrypt-resource")) {
            resultMap.put("code", "FAIL");
            resultMap.put("message", "失败");
        } else {
            resultMap.put("code", "SUCCESS");
            resultMap.put("message", "成功");
        }
        executorService.execute(() -> {
            Map<String, Object> resource = (Map<String, Object>) requestParmAsMap.get("resource");
            String associated_data = (String) resource.get("associated_data");
            String nonce = (String) resource.get("nonce");
            String ciphertext = (String) resource.get("ciphertext");
            AesUtil aesUtil = new AesUtil(apiV3.getBytes(StandardCharsets.UTF_8));
            try {
                String decryptToString = aesUtil.decryptToString(
                        associated_data.getBytes(StandardCharsets.UTF_8),
                        nonce.getBytes(StandardCharsets.UTF_8),
                        ciphertext);
                Map<String, Object> resultAsMap = (Map<String, Object>) JSON.parse(decryptToString);
                String attach = (String) resultAsMap.get("attach");
                Map<String, Object> parse = (Map<String, Object>) JSON.parse(attach);
                Integer peopleId = (Integer) parse.get("peopleId");
                People people = peopleFunction.queryGetOneString(JSON.toJSONString(new QueryWrapperVO().eq("id", peopleId)));
                if (people != null) {
                    people.setIsVip(1);
                    peopleFunction.updateByid(people);
                }
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }

        });
        return resultMap;
    }
}




























































